package com.gxc.service.log.mq;

import com.gxc.service.common.util.JsonUtil;
import com.gxc.service.log.entity.RequestInfoLogEntity;
import com.gxc.service.log.repository.RequestInfoLogRepository;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 请求日志Listener.
 *
 * @author GongXincheng
 * @since 2019-11-09 03:32
 */
@Slf4j
@Component
public class RequestInfoLogListener {

    @Resource
    private RequestInfoLogRepository requestInfoLogRepository;

    //@RabbitListener(bindings = @QueueBinding(value = @Queue(name = "${gxc.mq.queue.request-info-log}"), exchange = @Exchange(name = "${gxc.mq.exchange}", type = "topic")))
    @RabbitListener(queues = "${gxc.mq.queue.request-info-log}")
    public void consumer(Message message, Channel channel) throws IOException {
        boolean ackFlag = false;
        String messageBody = null;
        try {
            messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
            RequestInfoLogEntity entity = JsonUtil.parseObject(messageBody, RequestInfoLogEntity.class);
            requestInfoLogRepository.save(entity);
        } catch (Exception e) {
            ackFlag = true;
            log.error("{}, request info of log has error：{}", this.getClass().getSimpleName(), e.getMessage());
        } finally {
            // 如果没有异常信息，则"确认应答"，否则不应答
            if (!ackFlag) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                log.error("请求日志保存失败，未确认应答，message：{}", messageBody);
            }
        }
    }

}
